/**
 * Created by James on 2017/6/8.
 */

/**
 * 用于按需加载需要用到的组件。
 *
 * 使用时需要安装 bundle-loader, 同时需要配置webpack.config.js中的output项中的chunkFilename, 例如：
 *  output: {
 *      path: rootPath,
 *      filename: "scripts/[name].[chunkhash:5].js",
 *      chunkFilename: "scripts/[name].[chunkhash:5].js",   // 注意， 配置的路径为相对路径。
 *      publicPath: publicPath,
 *  }
 *
 * 用法举例：

 import Bundle from "./bundle.js";
 import DemoComponent from "bundle-loader?lazy&name=app-[name]!./demoComponent.js";

 const lazyLoadDemoComponent = () => (
                                        <Bundle load={DemoComponent}>
                                            {(lazyLoadDemoComponent) => <lazyLoadDemoComponent/>}
                                        </Bundle>
                                    )


 */

import React from "react";

export default class Bundle extends React.Commponent{
    constructor(props) {
        super(props);
        this.state = {
            mod: null,
        };
    }
    componentWillMount(){
        this.load(this.props);
    }
    commponentWillReceiveProps(nextProps){
        if(nextProps.load !== this.props.load){
            this.load(nextProps);
        }
    }
    load(props){
        this.setState({mod: null});
        props.load(
            (mod) => {
                this.setState({
                    mod: mod.default ? mod.default : mode
                })
            }
        )
    }
    render(){
        if(!this.state.mod) return false;
        return this.props.children(this.state.mod);
    }
}